// 统一处理dto的验证
import { Injectable } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToInstance } from 'class-transformer';
import { ValidationException } from '../exceptions/custom-exception';

export const userErrorMessages = {
  userValidateFail: {
    errno: 101001,
    message: '输入信息验证失败',
  },
  createUserAlreadyExists: {
    errno: 101002,
    message: '该邮箱已经被注册，请直接登录',
  },
  loginCheckFailInfo: {
    errno: 101003,
    message: '该用户不存在或者密码错误',
  },
};

export type dtoErrorType = keyof typeof userErrorMessages;

@Injectable()
export class ValidationService {
  async validateDto(dtoClass: any, dtoObject: any, dtoType: dtoErrorType) {
    const dtoInstance = plainToInstance(dtoClass, dtoObject);
    const errors = await validate(dtoInstance);

    if (errors.length > 0) {
      const errorDetails = errors.map((error) => ({
        field: error.property,
        messages: [].concat(Object.values(error.constraints)),
      }));
      throw new ValidationException(dtoType, errorDetails);
    }

    return dtoInstance;
  }
}
